import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'umi';
import { Modal, Space, Row, Col, Button } from 'antd';
import { Tree } from 'antd';
import TableDataBlock from '@/components/TableDataBlock';
import Categories from '@/components/ShareImgCollect/components/DraggableView/components/Cephalogram/components/manageMash/components/Categories';
import PopImgShow from '@/components/PopImgShow';
import aliOssUpload from '@/utils/aliOssUpload';
const manageMash = (props) => {
    const { visible = false, onClose, dispatch, loading, list, handleImage, contentType = 'image' } = props;
    const { show, details = {} } = visible;
    const { } = details;
    const childRef = useRef();
    useEffect(() => {
        if (!show) {
            setSelectedRowKeys([]);
        }
    }, [show]);
    const [categoryList, setCategoryList] = useState([]);
    const handleCallback = () => {
        if (childRef && childRef.current) {
            childRef.current.fetchGetData();
        }
    };
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState(['']);
    const rowSelection = {
        onChange: (val, selectedRows, info) => {
            setSelectedRowKeys(selectedRows);
        },
        selectedRowKeys: selectedRowKeys.map((item) => {
            return item.id.toString();
        }),
    };
    useEffect(() => {
        fetchData();
    }, []);
    useEffect(() => {
        handleCallback()
    }, [selectedKeys])
    const fetchData = () => {
        dispatch({
            type: 'liveStreaming/fetchListMaterialCategory',
            payload: {
                categoryType: contentType,
            },
            callback: (e) => {
                setCategoryList(e);
            },
        });
    };
    const searchItems = [{ label: '关键词', name: 'keyword' }];
    const openImagePicker = async () => {
        try {
            const fileHandle = await window.showOpenFilePicker({
                multiple: false, // 设置为 false 表示只能选择一个文件
                types: [
                    {
                        accept: {
                            'image/*': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg']
                        }
                    }
                ]
            });
            // 处理文件，例如读取内容
            const file = fileHandle.values().next().value;
            const image = await file.getFile();
            const img = await aliOssUpload(image)
            return img.toString()
        } catch (error) {
            console.error(error);
        }
    }
    const getColumns = [
        {
            title: '素材名称',
            dataIndex: 'materialName',
        },

        {
            title: '使用次数',
            dataIndex: 'useAmount',
        },
        {
            title: '图片',
            dataIndex: 'content',
            render: (e) => {
                const { url } = JSON.parse(e);
                return <PopImgShow width={40} url={url}></PopImgShow>;
            },
        },
    ];
    const modalProps = {
        title: <div>选择素材
            {contentType === 'image' && <Button onClick={async () => {
                let img = await openImagePicker()
                handleImage({
                    src: img
                })
                onClose()
            }} type='link'>直接上传图片</Button>}
        </div >,
        width: 1200,
        visible: typeof visible === 'boolean' ? visible : show,
        maskClosable: true,
        destroyOnClose: true,
        zIndex: 10010,
        onOk: () => {
            handleImage(
                selectedRowKeys.map((item) => {
                    const { content } = item;
                    let imgObj = JSON.parse(content);
                    const { url } = imgObj;
                    return {
                        ...item,
                        src: url,
                    };
                })[0],
            )
            onClose()
        }

    };

    return (
        <Modal {...modalProps} onCancel={onClose}>

            <Row>
                <Col span={6}>
                    <Categories
                        selectedKeys={selectedKeys}
                        setSelectedKeys={setSelectedKeys}
                        list={[
                            {
                                categoryName: `全部`,
                                id: '',
                                subMaterialCategoryList: categoryList,
                            },
                        ]}
                    ></Categories>
                </Col>
                <Col span={18}>
                    <TableDataBlock
                        style={{ width: '100%' }}
                        rowSelection={{
                            type: 'radio',
                            ...rowSelection,
                        }}
                        params={{
                            contentType: contentType,
                            status: '1',
                            categoryId: selectedKeys.toString()
                        }}
                        cRef={childRef}
                        loading={loading}
                        searchItems={searchItems}
                        columns={getColumns}
                        rowKey={(record) => `${record.id}`}
                        dispatchType="liveStreaming/fetchListMaterial"
                        {...list}
                    ></TableDataBlock>
                </Col>
            </Row>

        </Modal>
    );
};

export default connect(({ liveStreaming, loading }) => ({
    list: liveStreaming.materialList,
    loading: loading.models.liveStreaming,
}))(manageMash);
